package br.ufpb.di.ppgi.persistencia.em;

import javax.annotation.PreDestroy;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.ioc.ComponentFactory;
import br.ufpb.di.ppgi.util.logger.Logger;
import br.ufpb.di.ppgi.util.logger.LoggerFactory;

@Component
@SuppressWarnings("unused")
public class EntityManagerCreator implements ComponentFactory<EntityManager> {
	private static final Logger LOGGER = LoggerFactory.getLogger(EntityManagerFactoryCreator.class);

	private final EntityManager manager;

	public EntityManagerCreator(EntityManagerFactory factory) {
		LOGGER.customDebug("Construindo o EntityManager [ThreadID %d].", Thread.currentThread().getId());
		manager = factory.createEntityManager();
		LOGGER.customDebug("EntityManager construido com sucesso.", Thread.currentThread().getId());
	}
	
	public EntityManager getInstance() {
		return manager;
	}



	@PreDestroy
	private void destroy() {
		if (manager.isOpen()) {
			LOGGER.customDebug("Destruindo o EntityManager [ThreadID %d].", Thread.currentThread().getId());
			manager.close();
		} else
			LOGGER.warn("EntityManager já se encontrava fechado antes da destruição do componente.");
	}
}
